#!/usr/bin/python2.5
# -*- coding: utf-8 -*-
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import urllib

import tipfy
from tipfy.ext import i18n
from tipfy.ext.i18n import _
from tipfy.ext import jinja2
from tipfy.ext import wtforms
from tipfy.ext.wtforms import fields

from apps.pf_mobile import middleware
from apps.pf_mobile import pfapi
from apps.pf_mobile import wsgi
from apps.pf_mobile.handlers import search
from apps.pf_mobile.utils import jp_mobile_carriers
from apps.pf_mobile.utils import urlize

class BaseHandler(tipfy.RequestHandler):
  middleware = [middleware.UserAgentMiddleware]
  def head(self, **kwargs):
    return self.render_string('')

  def render_response(self, filename, **kwargs):
    return wsgi.MobileResponse(jinja2.render_template(
        filename, url_for=self.url_for, urlgettext=i18n.gettext,
        locale=i18n.get_locale(), **kwargs).encode('shift_jis', 'replace'),
                               mimetype='text/html')
  def render_string(self, string):
    if not isinstance(string, unicode):
      string = string.decode('utf-8')
    return wsgi.MobileResponse(string.encode('shift_jis'))

  def redirect_to(self, name, query_args={}, code=302, **kwargs):
    url = super(BaseHandler, self).url_for(name, **kwargs)
    if query_args:
      url += '?' + urllib.urlencode(query_args)
    return super(BaseHandler, self).redirect(url, code)

class RegistrationForm(wtforms.Form):
  author_name = fields.TextField(_(u'名'))
  identity_name = fields.TextField(_(u'Identity'))

class RedirectHandler(BaseHandler):
  def get(self, **kwargs):
    """Redirect to appropriate sites by User-Agent."""
    if self.request.is_mozilla:
      return self.redirect('http://japan.person-finder.appspot.com/?'
                           'redirect=0&suppress_redirect=yes')
    else:
      return self.redirect_to('index')

class IndexHandler(BaseHandler):
  def get(self, **kwargs):
    return self.render_response('index.html', form=None,
                                kddi=self.request.is_kddi)

  def post(self, **kwargs):
    if self.form.validate():
      return self.render_string(self.form.author_name.data)
    else:
      return self.render_string(_('Invalid Form'))

  @tipfy.cached_property
  def form(self):
    return RegistrationForm(self.request)


class SearchHandler(BaseHandler):
  def get(self, **kwargs):
    """Render a search form."""
    return self.render_response('search_form.html')

  def post(self, **kwargs):
    query = self.request.form.get('q')
    if not query:
      return self.render_response('search_form.html')
    api = pfapi.PfApi()
    carrier_url, is_mobile = jp_mobile_carriers.handle_phone_number(query)
    # If the query is a mobile number, don't query personfinder
    if is_mobile:
      if carrier_url:
        return self.redirect(carrier_url)
      else:
        return self.render_response('search_results.html',
                                    results=[],
                                    num=0,
                                    query=query)
    try:
      people, notes = api.search(query, 30)
    except pfapi.PfApiError:
      return self.render_string(
          (u'%s<a href="%s">%s</a>' % (_(u'検索できませんでした'),
                                       self.url_for('search'),
                                       _(u'もう一度検索する。'))))

    person_map = dict((person['person_record_id'], person) for person in people)
    for note in notes:
      if note['person_record_id'] in person_map and note.get('status'):
        person_map[note['person_record_id']].setdefault('notes', []).append(
            note)
    for person in people:
      person['home_joined_address'] = search.joinHomeAddress(person)
      if person.get('notes'):
        person['status'] = search.mapStatusText(person['notes'][-1]['status'])

    return self.render_response('search_results.html',
                                results = people,
                                num=len(people),
                                query=query)

class ViewHandler(BaseHandler):
  def get(self, **kwargs):
    """ Render a search result for person."""
    added = self.request.args.get('added')
    id_param = self.request.args.get('id')
    email_added = self.request.args.get('email_added')
    if not id_param:
      return self.render_string(_('ID not found'))

    api = pfapi.PfApi()
    try:
      people, notes = api.read(id_param)
    except pfapi.PfApiError:
      return self.render_string(u'%s<a href="%s?id=%s">%s</a>' % (
                                 _(u'閲覧できませんでした。'),
                                   self.url_for('view'),
                                   id_param,
                                   _(u'もう一度閲覧する。')))

    notes.reverse()
    for note in notes:
      note['text'] = [urlize.urlize(line) for line in
                      note.get('text', '').split('\n')]
      note['status'] = search.mapStatusSimple(note.get('status', ''))
    person_finder_url = ('%s/view?redirect=0&suppress_redirect=yes&subdomain'
                         '=%s&id=%s' % (api.pf, api.subdomain,
                                        people[0]['person_record_id']))
    if self.request.is_kddi:
      person_finder_url = ('device:pcsiteviewer?url=%s/view?redirect=0&'
                           'suppress_redirect=yes&subdomain=%s&id=%s' %
                           (api.pf, api.subdomain,
                            people[0]['person_record_id']))
    return self.render_response("person.html",
                                person=people[0],
                                notes=notes,
                                added=(added is not None),
                                person_finder_url=person_finder_url,
                                email_added = email_added,
                                kddi = self.request.is_kddi)
